<template>
  <div class="room-manager">
    <div class="room-header">
      <h3>房间管理</h3>
      <div class="connection-status" :class="connectionStatus">
        {{ getConnectionStatusText() }}
      </div>
    </div>

    <!-- 连接状态 -->
    <div v-if="!isConnected" class="connection-section">
      <el-button 
        type="primary" 
        @click="connectToServer"
        :loading="connectionStatus === 'connecting'"
        size="large"
      >
        连接到服务器
      </el-button>
      <div v-if="lastError" class="error-message">
        {{ lastError }}
      </div>
    </div>

    <!-- 房间操作 -->
    <div v-else class="room-actions">
      <!-- 加入房间 -->
      <div v-if="!currentRoom" class="join-room-section">
        <h4>加入房间</h4>
        <el-form :model="joinForm" label-width="80px">
          <el-form-item label="房间代码">
            <el-input 
              v-model="joinForm.roomCode" 
              placeholder="输入房间代码"
              maxlength="6"
              show-word-limit
            />
          </el-form-item>
          <el-form-item label="昵称">
            <el-input 
              v-model="joinForm.nickname" 
              placeholder="输入你的昵称"
              maxlength="20"
              show-word-limit
            />
          </el-form-item>
          <el-form-item label="颜色">
            <el-color-picker v-model="joinForm.color" />
          </el-form-item>
          <el-form-item>
            <el-button 
              type="primary" 
              @click="joinRoom"
              :disabled="!canJoinRoom"
              :loading="joining"
            >
              加入房间
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 房间信息 -->
      <div v-else class="room-info-section">
        <h4>房间信息</h4>
        <div class="room-details">
          <div class="detail-item">
            <span class="label">房间代码:</span>
            <span class="value">{{ currentRoomDisplay }}</span>
          </div>
          <div class="detail-item">
            <span class="label">状态:</span>
            <span class="value" :class="gameStatus">{{ getGameStatusText() }}</span>
          </div>
          <div class="detail-item">
            <span class="label">玩家数量:</span>
            <span class="value">{{ playerCount }}/{{ maxPlayers }}</span>
          </div>
        </div>

        <!-- 玩家列表 -->
        <div class="players-section">
          <h5>玩家列表</h5>
          <div class="players-list">
            <div 
              v-for="player in players" 
              :key="player.id"
              class="player-item"
              :class="{ 'current-player': player.id === currentPlayer?.id }"
            >
              <div class="player-color" :style="{ backgroundColor: player.color }"></div>
              <div class="player-info">
                <div class="player-nickname">{{ player.nickname }}</div>
                <div class="player-joined">{{ formatTime(player.joinedAt) }}</div>
              </div>
              <div v-if="player.id === currentPlayer?.id" class="player-badge">我</div>
            </div>
          </div>
        </div>

        <!-- 房间操作 -->
        <div class="room-controls">
          <el-button 
            v-if="isHost && canStartGame"
            type="success" 
            @click="startGame"
            size="large"
          >
            开始游戏
          </el-button>
          <el-button 
            v-if="isHost && gameStatus === 'playing'"
            type="warning" 
            @click="endGame"
            size="large"
          >
            结束游戏
          </el-button>
          <el-button 
            type="danger" 
            @click="leaveRoom"
            size="large"
          >
            离开房间
          </el-button>
        </div>
      </div>
    </div>

    <!-- 聊天区域 -->
    <div v-if="currentRoom" class="chat-section">
      <h4>聊天</h4>
      <div class="chat-messages" ref="chatContainer">
        <div 
          v-for="message in chatMessages" 
          :key="message.id"
          class="chat-message"
          :class="{ 'own-message': message.PlayerId === currentPlayer?.id }"
        >
          <div class="message-header">
            <span class="message-author">{{ message.PlayerId === currentPlayer?.id ? '你' : message.PlayerId }}</span>
            <span class="message-time">{{ formatTime(message.Timestamp || message.timestamp) }}</span>
          </div>
          <div class="message-content">{{ message.Message || message.content }}</div>
        </div>
      </div>
      <div class="chat-input">
        <el-input 
          v-model="chatMessage" 
          placeholder="输入消息..."
          @keyup.enter="sendChatMessage"
          maxlength="200"
          show-word-limit
        >
          <template #append>
            <el-button @click="sendChatMessage" :disabled="!chatMessage.trim()">
              发送
            </el-button>
          </template>
        </el-input>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick, watch } from 'vue'
import { useGameStore } from '@/stores/game'
import { createSignalRService } from '@/services/socketService'
import { ElMessage } from 'element-plus'

const gameStore = useGameStore()
const signalRService = createSignalRService(gameStore)

// 响应式数据
const joinForm = ref({
  roomCode: '',
  nickname: '',
  color: '#1890ff'
})
const joining = ref(false)
const chatMessage = ref('')
const chatContainer = ref(null)

// 从store获取状态
const currentRoom = computed(() => gameStore.currentRoom)
const currentRoomDisplay = computed(() => typeof gameStore.currentRoom === 'string' ? gameStore.currentRoom : (gameStore.currentRoom?.id || ''))
const gameStatus = computed(() => gameStore.gameStatus)
const players = computed(() => gameStore.players)
const maxPlayers = computed(() => gameStore.currentRoom?.maxPlayers || gameStore.roomInfo?.MaxPlayers || 6)
const playerCount = computed(() => gameStore.playerCount)
const currentPlayer = computed(() => gameStore.currentPlayer)
const isConnected = computed(() => gameStore.isConnected)
const connectionStatus = computed(() => gameStore.connectionStatus)
const lastError = computed(() => gameStore.lastError)
const isHost = computed(() => gameStore.isHost)
const chatMessages = computed(() => gameStore.chatMessages)
const canJoinRoom = computed(() => gameStore.canJoinRoom)

// 生命周期
onMounted(() => {
  setupSignalRListeners()
})

// 监听聊天消息，自动滚动到底部
watch(chatMessages, () => {
  nextTick(() => {
    scrollToBottom()
  })
})

// 设置SignalR事件监听器
function setupSignalRListeners() {
  signalRService.on('Connected', () => {
    gameStore.setConnectionState('connected')
    ElMessage.success('已连接到服务器')
  })

  signalRService.on('Reconnecting', () => {
    gameStore.setConnectionState('reconnecting')
    ElMessage.warning('正在重新连接...')
  })

  signalRService.on('Reconnected', () => {
    gameStore.setConnectionState('connected')
    ElMessage.success('重新连接成功')
  })

  signalRService.on('Disconnected', () => {
    gameStore.setConnectionState('disconnected')
    ElMessage.error('连接已断开')
  })

  signalRService.on('WelcomeMessage', (data) => {
    ElMessage.success(data.Message)
  })

  signalRService.on('PlayerJoined', (playerInfo) => {
    ElMessage.info(`${playerInfo.Nickname} 加入了房间`)
  })

  signalRService.on('PlayerLeft', (playerInfo) => {
    ElMessage.warning(`${playerInfo.Nickname} 离开了房间`)
  })

  signalRService.on('PlayerDisconnected', (playerInfo) => {
    ElMessage.error(`${playerInfo.Nickname} 断开连接`)
  })

  signalRService.on('GameStarted', () => {
    ElMessage.success('游戏开始！')
  })

  signalRService.on('GameEnded', () => {
    ElMessage.info('游戏结束')
  })

  signalRService.on('ChatMessage', (messageData) => {
    gameStore.addChatMessage(messageData)
  })

  signalRService.on('RoomStateUpdated', (roomState) => {
    gameStore.setRoomInfo(roomState)
  })

  signalRService.on('RoomInfo', (roomInfo) => {
    gameStore.setRoomInfo(roomInfo)
  })

  signalRService.on('RoomNotFound', () => {
    ElMessage.error('房间不存在')
    joining.value = false
  })

  signalRService.on('MaxReconnectAttemptsReached', () => {
    ElMessage.error('连接失败，请检查网络后重试')
    gameStore.setConnectionState('disconnected')
  })
}

// 连接到服务器
async function connectToServer() {
  try {
    gameStore.setConnectionState('connecting')
    await signalRService.connect()
  } catch (error) {
    gameStore.setError(error.message)
    gameStore.setConnectionState('disconnected')
  }
}

// 加入房间
async function joinRoom() {
  if (!joinForm.value.roomCode.trim() || !joinForm.value.nickname.trim()) {
    ElMessage.warning('请填写完整的房间信息')
    return
  }

  try {
    joining.value = true
    const stablePlayerId = generatePlayerId()
    await signalRService.joinRoom(
      joinForm.value.roomCode.trim().toUpperCase(),
      stablePlayerId,
      joinForm.value.nickname.trim(),
      joinForm.value.color
    )
    
    gameStore.setRoom(joinForm.value.roomCode.trim().toUpperCase())
    gameStore.setCurrentPlayer({
      id: stablePlayerId,
      nickname: joinForm.value.nickname.trim(),
      color: joinForm.value.color
    })
    
    // 主动拉取一次房间信息，确保玩家列表立刻同步
    await signalRService.getRoomInfo(joinForm.value.roomCode.trim().toUpperCase())
    
    ElMessage.success('成功加入房间！')
  } catch (error) {
    ElMessage.error('加入房间失败：' + error.message)
  } finally {
    joining.value = false
  }
}

// 离开房间
async function leaveRoom() {
  try {
    await signalRService.leaveRoom(currentRoomDisplay.value, currentPlayer.value.id)
    gameStore.clearRoom()
    ElMessage.info('已离开房间')
  } catch (error) {
    ElMessage.error('离开房间失败：' + error.message)
  }
}

// 开始游戏
async function startGame() {
  try {
    await signalRService.startGame(currentRoom.value)
  } catch (error) {
    ElMessage.error('开始游戏失败：' + error.message)
  }
}

// 结束游戏
async function endGame() {
  try {
    await signalRService.endGame(currentRoom.value)
  } catch (error) {
    ElMessage.error('结束游戏失败：' + error.message)
  }
}

// 发送聊天消息
async function sendChatMessage() {
  if (!chatMessage.value.trim()) return
  
  try {
    await signalRService.sendChatMessage(
      currentRoom.value,
      currentPlayer.value.id,
      chatMessage.value.trim()
    )
    chatMessage.value = ''
  } catch (error) {
    ElMessage.error('发送消息失败：' + error.message)
  }
}

// 滚动聊天到底部
function scrollToBottom() {
  if (chatContainer.value) {
    chatContainer.value.scrollTop = chatContainer.value.scrollHeight
  }
}

// 生成玩家ID
function generatePlayerId() {
  return 'player_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9)
}

// 格式化时间
function formatTime(timestamp) {
  if (!timestamp) return ''
  const date = new Date(timestamp)
  return date.toLocaleTimeString('zh-CN', { 
    hour: '2-digit', 
    minute: '2-digit' 
  })
}

// 获取连接状态文本
function getConnectionStatusText() {
  const statusMap = {
    disconnected: '未连接',
    connecting: '连接中...',
    connected: '已连接',
    reconnecting: '重连中...'
  }
  return statusMap[connectionStatus.value] || '未知'
}

// 获取游戏状态文本
function getGameStatusText() {
  const statusMap = {
    waiting: '等待中',
    playing: '游戏中',
    finished: '已结束'
  }
  return statusMap[gameStatus.value] || '未知'
}
</script>

<style scoped>
.room-manager {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  padding: 20px;
  max-width: 400px;
}

.room-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 2px solid #f0f0f0;
}

.room-header h3 {
  margin: 0;
  color: #333;
  font-size: 18px;
  font-weight: 600;
}

.connection-status {
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 500;
}

.connection-status.disconnected {
  background: #ffebee;
  color: #c62828;
}

.connection-status.connecting {
  background: #fff3e0;
  color: #ef6c00;
}

.connection-status.connected {
  background: #e8f5e8;
  color: #2e7d32;
}

.connection-status.reconnecting {
  background: #fff3e0;
  color: #ef6c00;
}

.connection-section {
  text-align: center;
  padding: 20px 0;
}

.error-message {
  color: #d32f2f;
  margin-top: 10px;
  font-size: 14px;
}

.room-actions {
  margin-bottom: 20px;
}

.join-room-section h4,
.room-info-section h4 {
  margin: 0 0 15px 0;
  color: #555;
  font-size: 16px;
  font-weight: 600;
}

.room-details {
  margin-bottom: 20px;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.detail-item .label {
  color: #666;
  font-weight: 500;
}

.detail-item .value {
  color: #333;
  font-weight: 600;
}

.value.waiting {
  color: #2196f3;
}

.value.playing {
  color: #4caf50;
}

.value.finished {
  color: #ff9800;
}

.players-section {
  margin-bottom: 20px;
}

.players-section h5 {
  margin: 0 0 10px 0;
  color: #555;
  font-size: 14px;
  font-weight: 600;
}

.players-list {
  max-height: 200px;
  overflow-y: auto;
}

.player-item {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  margin-bottom: 8px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 2px solid transparent;
}

.player-item.current-player {
  border-color: #2196f3;
  background: #e3f2fd;
}

.player-color {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  margin-right: 12px;
  border: 2px solid #ddd;
}

.player-info {
  flex: 1;
}

.player-nickname {
  font-weight: 600;
  color: #333;
  font-size: 14px;
}

.player-joined {
  font-size: 12px;
  color: #666;
  margin-top: 2px;
}

.player-badge {
  background: #2196f3;
  color: white;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.room-controls {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.room-controls .el-button {
  width: 100%;
}

.chat-section {
  border-top: 2px solid #f0f0f0;
  padding-top: 20px;
}

.chat-section h4 {
  margin: 0 0 15px 0;
  color: #555;
  font-size: 16px;
  font-weight: 600;
}

.chat-messages {
  height: 200px;
  overflow-y: auto;
  background: #f8f9fa;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 15px;
}

.chat-message {
  margin-bottom: 12px;
  padding: 8px 12px;
  background: white;
  border-radius: 8px;
  border-left: 3px solid #e0e0e0;
}

.chat-message.own-message {
  border-left-color: #2196f3;
  background: #e3f2fd;
}

.message-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
}

.message-author {
  font-weight: 600;
  color: #333;
  font-size: 12px;
}

.message-time {
  font-size: 11px;
  color: #666;
}

.message-content {
  color: #333;
  font-size: 14px;
  line-height: 1.4;
}

.chat-input {
  display: flex;
  gap: 10px;
}

.chat-input .el-input {
  flex: 1;
}

/* 滚动条样式 */
.chat-messages::-webkit-scrollbar,
.players-list::-webkit-scrollbar {
  width: 6px;
}

.chat-messages::-webkit-scrollbar-track,
.players-list::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.chat-messages::-webkit-scrollbar-thumb,
.players-list::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.chat-messages::-webkit-scrollbar-thumb:hover,
.players-list::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .room-manager {
    max-width: 100%;
    margin: 0 10px;
  }
}
</style>
